<?php
namespace app\index\controller;


/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);

/**
 * 聊天主逻辑
 * 主要是处理 onMessage onClose 
 */
use \GatewayWorker\Lib\Gateway;
use think\Session;
class Events
{
   /**
    * 有消息时
    * @param int $client_id
    * @param mixed $message
    */
   public static function onMessage($client_id, $message)
   {
        // debug
        echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id session:".json_encode($_SESSION)." onMessage:".$message."\n";
        
        // 客户端传递的是json数据
        $message_data = json_decode($message, true);
        if(!$message_data)
        {
            return ;
        }
        
        // 根据类型执行不同的业务
        switch($message_data['type'])
        {
            // 客户端回应服务端的心跳
            case 'pong':
                return;
            // 客户端连接成功获取消息
            case 'login':
                $id = $message_data['id'];
                $client_name = htmlspecialchars($message_data['client_name']);
                $_SESSION['id'] = $id;
                $_SESSION['client_name'] = $client_name;
                if($client_name == 'sender'){
                    $_SESSION['sender'] = $client_id;
                }elseif ($client_name == 'receiver'){
                    $_SESSION['receiver'] = $client_id;
                }


                $new_message = array('type'=>$message_data['type'], 'client_id'=>$client_id, 'client_name'=>htmlspecialchars($client_name), 'time'=>date('Y-m-d H:i:s'),'msg'=>'success');
               Gateway::sendToClient($client_id,json_encode($new_message));

                return;
            case 'test':
                Gateway::sendToClient($client_id,json_encode("123"));
                return;
            case 'stream':
//                if(!isset($_SESSION['receiver']))
//                {
//                    throw new \Exception("\$_SESSION['receiver'] not set. client_ip:{$_SERVER['REMOTE_ADDR']}");
//                }
                Gateway::sendToAll(json_encode($message_data));

//                return;
                return;
            // 客户端发言 message: {type:say, to_client_id:xx, content:xx}
            case 'control':

                Gateway::sendToAll(json_encode($message_data));
                return;
        }
   }
   
   /**
    * 当客户端断开连接时
    * @param integer $client_id 客户端id
    */
   public static function onClose($client_id)
   {
       // debug
       echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id onClose:''\n";
       
       // 从房间的客户端列表中删除
       if(isset($_SESSION['room_id']))
       {
           $room_id = $_SESSION['room_id'];
           $new_message = array('type'=>'logout', 'from_client_id'=>$client_id, 'from_client_name'=>$_SESSION['client_name'], 'time'=>date('Y-m-d H:i:s'));
           Gateway::sendToGroup($room_id, json_encode($new_message));
       }
   }
  
}
